package control;

import java.io.*;
import java.net.*;
import java.util.*;


import sms.SmsBuffer;
import utility.Index;


import dbmanager.DBManager;

public class ClientWatch extends Thread
{
	public void run()
	{
		
	
		int port = 9999;
		try
		{
			ServerSocket server = new ServerSocket(port,5);
			System.out.println("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			while(true)
			{
				Socket connection = server.accept();
				if(connection !=null)
				{
					System.out.println(connection.getInetAddress().getHostName());
				}
				try
				{
					System.out.println("control::ClientWatch::run()::Connection established with "+connection);
					ClientProcess input = new ClientProcess(connection);
					input.start();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
}

class ClientProcess extends Thread
{
	
	Socket connection;
	DBManager database;
	public ClientProcess(Socket connection)
	{
		 ;
	
		database = new DBManager();
		database.getConnect();
		try
		{
			this.connection = connection;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void run()
	{
		 
	
		try
		{
			String Username=null;
			String request=null;
						 
			
			BufferedReader IncomingRequest = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			Username =  IncomingRequest.readLine();
			request  = IncomingRequest.readLine();
			if(Index.indexOf(request, "#")==-1)
			{
				SendResponse sendresponse = new SendResponse(connection,"password not present",Username,request);
				sendresponse.start();
			}
			System.out.println("\ncontrol::ClientProcess::run()::Client user name is -->"+Username);
			System.out.println("\ncontrol::ClientProcess::run()::Incoming Request is-->"+request);
		
			if(Username.startsWith("TO:")==false)
			{
				SmsControl control = new SmsControl(Username, request,database);
				StringBuffer response=new StringBuffer();
				Vector<Object> messageVector = new Vector<Object>();
				messageVector=control.splitRequest();
				
				for(Object object : messageVector)
				{
					Hashtable<Object,Object> h1 = (Hashtable<Object, Object>)object;
					response.append(h1);
				}
				/*h1 = control.messageProcessing();
				
				
				if(h1.containsKey("ErrorUser")==false)
				{
					h2 = control.requestProcess();
					response.append(h2);
					h1.clear();
					h2.clear();
				}
				else
				{
					System.out.println("Unable to Find user");
					h1.put("ErrorUser", "Unable to Find user or password");
					database.pLog.Logger.append("Error User :: Unable to Find user or password");
					response.append(h1);
				}*/
				char[] strCs = response.toString().toCharArray();
				response = new StringBuffer();
				for(int i=0;i<strCs.length;i++)
				{
					if(strCs[i]=='{'||strCs[i]=='}')
					{
						response.append(' ');
					}
					else
						response.append(strCs[i]);
				}
				response = new StringBuffer(response.toString().replace("\t", " "));
				response = new StringBuffer(response.toString().replace("\n", " "));
				SendResponse sendresponse = new SendResponse(connection,response.toString(),Username,request);
				sendresponse.start();
			}
			else
			{
				Username = Username.substring(Username.indexOf(':'));
				System.out.println("control::ClientProcess::run()::Message Delivery Report for user "+Username);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
			
				database.closeConnection();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		
	}
}

class SendResponse extends Thread
{
	PrintStream outputResponse;
	Socket connection;
	String response;
	String Username;
	
	public SendResponse(Socket connection,String response,String Username,String request)
	{
		
	
		try
		{
			this.connection = connection;
			this.response = request + " :: REPLY :: "+response;
			this.Username = Username;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
	public void run()
	{
		
	
		try
		{
			outputResponse= new PrintStream(connection.getOutputStream());
			System.out.println(connection);
			//out.write("I'm sending u the response");
			System.out.println("control::SendResponse::run()::The response is : "+response);
			outputResponse.flush();
			//outputResponse.println("The response is");
			//outputResponse.println(Username);
			outputResponse.flush();
			outputResponse.println(response);
			//out.flush();
			if(response.toLowerCase().contains("error"))
			{
				SmsBuffer sms = new SmsBuffer();
				sms.addBufferLog(Username, response);
			}	
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}	
	}
}